package java.com.codingmanage.dao.hibernate;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

public class HibernateSupportDAO<T> {
	
	public HibernateSupportDAO() {
		sessionFactory = SessionFactoryUtils.getInvocation().getSessionFactory();
	}

	Session session;
	SessionFactory  sessionFactory;
	private Class entityClass=(Class)((ParameterizedType) getClass()
			.getGenericSuperclass()).getActualTypeArguments()[0];;
	
	public Long save(T obj) {
		session=sessionFactory.openSession();
		Transaction t=session.beginTransaction();
		t.begin();
		Serializable id=session.save(obj);
		t.commit();
		session.close();
		System.out.println( id );
		return (Long) id;
	}

	public Long update(T obj) {
		Long id=(Long) session.getIdentifier(obj);
		session=sessionFactory.openSession();
		Transaction t=session.beginTransaction();
		t.begin();
		session.update(obj);
		t.commit();
		session.close();
		System.out.println( id );
		return (Long) id;
	}

	public Long delete(T obj) {
		Long id=(Long) session.getIdentifier(obj);
		session=sessionFactory.openSession();
		Transaction t=session.beginTransaction();
		t.begin();
		session.delete(obj);
		t.commit();
		session.close();
		System.out.println( id );
		return (Long) id;
	}

	public T get(Long id) {
		session=sessionFactory.openSession();
		return (T) session.get(entityClass, id);
	}

	public List<T> findAll() {
		Criteria c=session.createCriteria(entityClass);
		//c.add(Restrictions.like(propertyName, value));
		List<T> list = c.list();
		return list;
	}
	
	

}
